package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.startegy.OrderTradeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Service
@Slf4j
//实现ApplicationContextAware接口，在容器启动时，会自动调用setApplicationContext方法，将容器中的所有OrderTradeStrategy实现类对象，
public class OrderTradeStrategyContext implements ApplicationContextAware {
    //定义一个map类的成员变量,用来管理OrderTradeStrategy这个接口的实现类对象
    private static final Map<String, OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<>();

    //根据itemType获取对应的OrderTradeStrategy对象
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        return ORDER_TRADE_STRATEGY_MAP.get(itemType);
    }

    //该方法是框架帮我们进行调用的
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();
            ORDER_TRADE_STRATEGY_MAP.put(itemType, orderTradeStrategy);
        });
        log.info("OrderTradeStrategy策略实现类的对象进行统一的管理");
    }
}
